﻿using Core;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MQTTnet.Server;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace BGYMqttServer.HostedServices
{
    /// <summary>
    /// 表示mqtt服务后台服务
    /// </summary>
    public class MqttServerHostedService : HostedService
    {
        private readonly IMqttServer mqttServer;
        private readonly ILogger<MqttServerHostedService> logger;
        private readonly IOptions<MqttServerOptionsBuilder> optionsBuilder;

        /// <summary>
        /// mqtt服务后台服务
        /// </summary>
        /// <param name="services"></param>
        /// <param name="mqttServer"></param>
        /// <param name="logger"></param>
        /// <param name="options"></param>
        public MqttServerHostedService(
            IServiceProvider services,
            IMqttServer mqttServer,
            ILogger<MqttServerHostedService> logger,
            IOptions<MqttServerOptionsBuilder> options) : base(services)
        {
            this.mqttServer = mqttServer;
            this.logger = logger;
            this.optionsBuilder = options;
        }

        /// <summary>
        /// 启动服务
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        protected override async Task StartAsync(CancellationToken stoppingToken)
        {
            var options = this.optionsBuilder.Value.Build();
            await this.mqttServer.StartAsync(options);
            this.logger.LogInformation($"Now listening on: mqtt://{options.DefaultEndpointOptions.BoundInterNetworkAddress}:{options.DefaultEndpointOptions.Port}");
        }
    }
}
